package com.nyist.mq.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.nyist.autoconfigure.RocketMQConfigProperties;
import com.nyist.entity.User;
import com.nyist.mq.enums.RocketEnum;
import com.nyist.mq.service.ProducerTXService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 1.
 *
 * @ClassName ProducerTXServiceImpl
 * @Description
 * @Author xiaoyang
 * @Date 2023/03/29/14:21
 */
@Slf4j
@Service
public class ProducerTXServiceImpl implements ProducerTXService {
    private static String topic;
    private static String tag;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private RocketMQConfigProperties rocketMQConfigProperties;

    @PostConstruct
    public void init() {
        topic = rocketMQConfigProperties.getTopic();
        tag = RocketEnum.TAG_TX_CHARGE.getCode();
    }

    @Override
    public TransactionSendResult sendHalfMessage(User user) {
        // 使用 hutool 生成简单的 事务id, 直接去掉了 "-"
        // String transactionId = UUID.randomUUID().toString().replace("-", "");
        String transactionId = IdUtil.fastSimpleUUID();
        log.info("【发送半消息】transactionId={}", transactionId);

        // 发送事务消息（生产者所在事务组-默认生产者组，参1：topic+tag，参2：消息体(可以传参)，参3：发送参数）
        MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor();
        headerAccessor.setHeader(RocketMQHeaders.TRANSACTION_ID,transactionId);
        Message<User> toConsumerMessage = MessageBuilder.withPayload(user).setHeaders(headerAccessor).build();
        String destination = topic + ":" + tag;

        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(destination, toConsumerMessage, user);

        log.info("【发送半消息】sendResult={}", JSON.toJSONString(transactionSendResult));
        return transactionSendResult;
    }
}
